package com.store.utils;

import com.aliyun.ocr_api20210707.Client;
import com.aliyun.ocr_api20210707.models.RecognizeAllTextRequest;
import com.aliyun.ocr_api20210707.models.RecognizeAllTextResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.google.gson.Gson;
import com.store.configure.AliyunOCRConfig;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.util.Map;

/**
 * @author lizg
 * @Description: 身份证识别接口
 * @date 2022/8/23 18:02
 */
public class AliyunOCRUtil {

    public static String idCardAnalysis(InputStream inputStream, AliyunOCRConfig aliyunOCRConfig) throws Exception {
        if (aliyunOCRConfig == null
                || !StringUtils.hasText(aliyunOCRConfig.getEndpoint())
                || !StringUtils.hasText(aliyunOCRConfig.getAccessKeyId())
                || !StringUtils.hasText(aliyunOCRConfig.getAccessKeySecret())
        ) throw new RuntimeException("IdCard analysis param is not complete, please check and try again");
        try {
            Map map = sendRequest(inputStream, null, aliyunOCRConfig);
            return String.valueOf(map.get("Content")).replaceAll("\\s", "");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    public static Map idCardAnalysis(String path, AliyunOCRConfig aliyunOCRConfig) throws Exception {
        if (!path.startsWith("http"))
            throw new RuntimeException("path must start with http, please check and try again");
        return sendRequest(null, path, aliyunOCRConfig);
    }

    private static Map sendRequest(InputStream inputStream, String path, AliyunOCRConfig aliyunOCRConfig) throws Exception {
        try {
            Config config = new Config()
                    .setAccessKeyId(aliyunOCRConfig.getAccessKeyId())
                    .setAccessKeySecret(aliyunOCRConfig.getAccessKeySecret());
            config.endpoint = aliyunOCRConfig.getEndpoint();
            Client client = new Client(config);

            // 访问的域名
            config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
            RecognizeAllTextRequest request = new RecognizeAllTextRequest()
                    .setType("Advanced")        // 指定 Type（此参数为必填参数）
                    .setOutputOricoord(true);
            if (inputStream != null) request.setBody(inputStream);
            else if (path != null) request.setUrl(path);
            RuntimeOptions runtime = new RuntimeOptions();

            // 您也可以在 request 中指定更多参数。例如对于 Type=Advanced，可以指定 OutputCharInfo=true（输出单字信息）
            RecognizeAllTextRequest.RecognizeAllTextRequestAdvancedConfig advancedConfig = new RecognizeAllTextRequest.RecognizeAllTextRequestAdvancedConfig()
                    .setOutputCharInfo(true);
            request.setAdvancedConfig(advancedConfig);
            RecognizeAllTextResponse response = client.recognizeAllText(request);
            System.out.println(new Gson().toJson(response.getBody().getData().toMap()));
            return response.getBody().getData().toMap();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
